﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using University.Workshop.DataAccess;
using System.Threading;
using System.Globalization;
using University.Workshop.DataAccess.LanguagePack.ClientLanguagePack;
using System.Net;
using University.Workshop.Model;
using University.Workshop.Business;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace University.Workshop.ClientApp.PokerGame.PokerTable
{
    /// <summary>
    /// Interaction logic for CreateTableOption.xaml
    /// </summary>
    public partial class CreateTableOption : Window
    {
        Client Player = new Client();
        RelationshipsManager Relations;
        Client Level = new Client();
 
        ListBox Tables;
        DataGrid TablesData;
        private User user;
        private string LanguageSelected;
        private string MessageComboBoxLevelOptionNoRule;
        private string MessageComboBoxLevelOptionBegginer;
        private string MessageComboBoxLevelOptionCowboy;
        private string MessageComboBoxLevelOptionHero;
        private string MessageComboBoxLevelOptionExpert;
        private string MessageComboBoxLevelOptionGenius;
        private string MessageErrorTheIPIsInUse;
        private string MessageErrorAllFieldsAreRequiered;
        private string MessageErrorTheMinimusBetIsGreaterThanTheMaximusBet;
        private string MessageErrorYouDontHaveChipsSufficient;

        private Workshop.ClientApp.PokerTable table = null;        

        private long MinimusBet;
        private long MaximusBet;                

        public CreateTableOption()
        {
            InitializeComponent();

            ComboBoxInitializeComponent();
        }

        public CreateTableOption(User user)
        {
            InitializeComponent();

            this.user = user;
            this.textBox_TableName.Text = "Game Of " + user.Name;            

            ComboBoxInitializeComponent();
            this.MinimusBet = -1;
            this.MaximusBet = -1;
        }

        public CreateTableOption(User user, string Language)
        {
            InitializeComponent();

            this.user = user;
            this.textBox_TableName.Text = "Game Of " + user.Name;

            this.LanguageSelected = Language;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.LanguageSelected);
            ApplyLanguage();

            ComboBoxInitializeComponent();
            this.MinimusBet = 0;
            this.MaximusBet = 0;
        }

        public CreateTableOption(User user, string language, ListBox tables, RelationshipsManager relations)
        {
            InitializeComponent();

            this.user = user;
            this.textBox_TableName.Text = "Game Of " + user.Name;

            this.LanguageSelected = language;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.LanguageSelected);
            ApplyLanguage();

            ComboBoxInitializeComponent();

            this.Tables = tables;
            this.Relations = relations;
            this.MinimusBet = -1;
            this.MaximusBet = -1;
        }

        public CreateTableOption(User user, string language, DataGrid tables, RelationshipsManager relations)
        {
            InitializeComponent();

            this.user = user;
            this.textBox_TableName.Text = "Game Of " + user.Name;

            this.LanguageSelected = language;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.LanguageSelected);
            ApplyLanguage();

            ComboBoxInitializeComponent();

            this.TablesData = tables;
            this.Relations = relations;
            this.MinimusBet = -1;
            this.MaximusBet = -1;
        }

        private void ComboBoxInitializeComponent()
        {
            //ComboBox Player Limitation, defect -> 3 (5 players)         
            this.comboBox_MaximunPlayer.Items.Add("2");
            this.comboBox_MaximunPlayer.Items.Add("3");
            this.comboBox_MaximunPlayer.Items.Add("4");
            this.comboBox_MaximunPlayer.Items.Add("5");
            this.comboBox_MaximunPlayer.SelectedIndex = 3;


            //ComboBox Level Limitation, defect -> No Rule
            this.comboBox_LevelLimitation.Items.Add(this.MessageComboBoxLevelOptionNoRule.Replace(" ", "_"));
            this.comboBox_LevelLimitation.Items.Add(this.MessageComboBoxLevelOptionBegginer);
            this.comboBox_LevelLimitation.Items.Add(this.MessageComboBoxLevelOptionCowboy);
            this.comboBox_LevelLimitation.Items.Add(this.MessageComboBoxLevelOptionHero);
            this.comboBox_LevelLimitation.Items.Add(this.MessageComboBoxLevelOptionGenius);
            this.comboBox_LevelLimitation.Items.Add(this.MessageComboBoxLevelOptionExpert);
            this.comboBox_LevelLimitation.SelectedIndex = 0;
        }

        private void button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void ApplyLanguage()
        {
            this.Title = ClientLanguagePack.PokerGamePokerTableCreateTableOptionTitle;
            
            this.label_CreateANewTable.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionLabelCreateANewTable;
            this.label_InsertNameTable.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionLabelInsertNameTable;
            this.label_LevelLimitation.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionLabelLevelLimitation;
            this.label_MaximunBet.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionLabelMaximunBet;
            this.label_MaximunPlayer.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionLabelMaximunPlayer;
            this.label_MinimalBet.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionLabelMinimalBet;            

            //Buttons properties
            this.button_Create.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionButtonCreate;
            this.button_Cancel.Content = ClientLanguagePack.PokerGamePokerTableCreateTableOptionButtonCancel;

            //Messages
            this.MessageComboBoxLevelOptionNoRule = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageComboBoxLevelOptionNoRule;
            this.MessageComboBoxLevelOptionHero = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageComboBoxLevelOptionHero;
            this.MessageComboBoxLevelOptionGenius = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageComboBoxLevelOptionGenius;
            this.MessageComboBoxLevelOptionExpert = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageComboBoxLevelOptionExpert;
            this.MessageComboBoxLevelOptionCowboy = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageComboBoxLevelOptionCowboy;
            this.MessageComboBoxLevelOptionBegginer = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageComboBoxLevelOptionBegginer;
            this.MessageErrorTheIPIsInUse = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageErrorTheIPIsInUse;
            this.MessageErrorAllFieldsAreRequiered = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageErrorAllFieldsAreRequiered;
            this.MessageErrorTheMinimusBetIsGreaterThanTheMaximusBet = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageErrorTheMinimusBetIsGreaterThanTheMaximusBet;
            this.MessageErrorYouDontHaveChipsSufficient = ClientLanguagePack.PokerGamePokerTableCreateTableOptionMessageErrorYouDontHaveChipsSufficient;
        }

        private void button_Create_Click(object sender, RoutedEventArgs e)
        {
            string Message = CreateNewTable();
            if (string.IsNullOrEmpty(Message) != true)
            {
                MessageBox.Show(Message, ":-(");
            }
            else
            {
                this.Close();
            }
        }

        private string LocalIPAddress()
        {
            string strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
            foreach (IPAddress IPAddress in iphostentry.AddressList)
            {
                return (IPAddress.ToString());
            }
            return (null);
        }

        private string CreateNewTable()
        {
            if (!String.IsNullOrEmpty(this.textBox_TableName.Text) &&
                !String.IsNullOrEmpty(this.textBox_MinimalBet.Text) &&
                !String.IsNullOrEmpty(this.textBox_MaximunBet.Text))
            {
                if (this.MinimusBet >= this.MaximusBet)
                {
                    this.textBox_MinimalBet.SelectAll();
                    return(this.MessageErrorTheMinimusBetIsGreaterThanTheMaximusBet);
                }
                else
                {
                    if (user.Chips <= this.MinimusBet ||
                        user.Chips < this.MaximusBet)
                    {
                        return (this.MessageErrorYouDontHaveChipsSufficient + " " + this.user.Chips);
                    }
                    else
                    {
                        bool Found = false;
                        string IP = LocalIPAddress();
                        foreach (TableProperties Item in TablesData.Items)
                        {
                            if (Item.IPAddress == IP)
                            {
                                Found = true;
                            }
                        }
                        if (!Found)
                        {
                            string NameTable = this.textBox_TableName.Text;
                            NameTable = NameTable.Replace(" ", "#");

                            string TotalPlayerLimitation = this.comboBox_MaximunPlayer.SelectedItem.ToString();
                            string LevelLimitation = this.comboBox_LevelLimitation.SelectedItem.ToString();
                            Player.Send("22 " + IP + " " + user.Name + " " + TotalPlayerLimitation + " " + LevelLimitation + " " + this.MaximusBet + " " + this.MinimusBet + " " + NameTable);
                            
                            Collection<LevelDatabase> levels = Level.GetAllLevels;

                            TableProperties TableRules = new TableProperties() { TableName = NameTable, UserCreator = user.Name, IPAddress = IP, MaximumBet = this.MaximusBet.ToString(), MinimumBet = this.MinimusBet.ToString(), RuleLevel = LevelLimitation, TotalPlayers = TotalPlayerLimitation };

                            table = new ClientApp.PokerTable(2999, user, Relations, levels, TableRules,this.LanguageSelected);

                            table.ShowDialog();
                            Player.Send("14 " + user.Name + " " + user.Chips + " " + user.UserLevel + " " + user.TimeWon);
                            Player.Send("24");
                            return (null);
                        }
                        else
                        {
                            return (this.MessageErrorTheIPIsInUse);                            
                        }
                    }
                }
            }
            else
            {
                return(this.MessageErrorAllFieldsAreRequiered);
            }
        }

        private void TextBoxTableNameTextChanged(object sender, TextChangedEventArgs e)
        {
            if (String.IsNullOrEmpty(this.textBox_TableName.Text) == false)
            {
                //If the user name don't complete the character orders
                string UserNamePattern = "^[\\sa-zA-Z0-9_-]{1,30}$";
                if (Regex.IsMatch(this.textBox_TableName.Text, UserNamePattern))
                {
                    this.button_Create.IsEnabled = true;
                }
                else
                {                    
                    this.button_Create.IsEnabled = false;

                    string WordToChange = this.textBox_TableName.Text;
                    int Pointer = WordToChange.Length - 1;
                    WordToChange = WordToChange.Remove(Pointer);
                    this.textBox_TableName.Text = WordToChange;
                    this.textBox_TableName.Select(this.textBox_TableName.Text.Length, 0);
                }
            }
            else
            {
                this.button_Create.IsEnabled = false;
            }
        }

        private void TextBoxMinimalBetTextChanged(object sender, TextChangedEventArgs e)
        {
            if (String.IsNullOrEmpty(this.textBox_MinimalBet.Text) == false)
            {
                try
                {
                    long AuxiliarMinimal = Convert.ToInt64(this.textBox_MinimalBet.Text);
                    this.MinimusBet = AuxiliarMinimal;
                }
                catch (Exception)
                {
                    string WordToChange = this.textBox_MinimalBet.Text;
                    int Pointer = WordToChange.Length - 1;
                    WordToChange = WordToChange.Remove(Pointer);
                    this.textBox_MinimalBet.Text = WordToChange;
                    this.textBox_MinimalBet.Select(this.textBox_MinimalBet.Text.Length, 0);
                }
            }
            else
            {
                this.MinimusBet = -1;
            }
        }

        private void TextBoxMaximunBetTextChanged(object sender, TextChangedEventArgs e)
        {
            if (String.IsNullOrEmpty(this.textBox_MaximunBet.Text) == false)
            {
                try
                {
                    long AuxiliarMaximun = Convert.ToInt64(this.textBox_MaximunBet.Text);
                    this.MaximusBet = AuxiliarMaximun;
                }
                catch (Exception)
                {
                    string WordToChange = this.textBox_MaximunBet.Text;
                    int Pointer = WordToChange.Length - 1;
                    WordToChange = WordToChange.Remove(Pointer);
                    this.textBox_MaximunBet.Text = WordToChange;
                    this.textBox_MaximunBet.Select(this.textBox_MaximunBet.Text.Length, 0);
                }
            }
            else
            {
                this.MaximusBet = -1;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (table != null)
            {
                table.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                 new Action(delegate()
                 {

                     if (table.IsLoaded)
                         table.Close();

                 }));

            }
        }
    }
}
